import sys
import os
import subprocess
import time
import logging
import logging.handlers

EXEC_PATH = '/var/www/newznab/misc/update_scripts/justpostprocessing.php'
LOGFILE = '/home/robert/justpp.log'
RECALL = '/tmp/backup/recall.txt'
LOG_FORMAT = '%(asctime)s - %(message)s'

lgr = logging.getLogger('postproc')
lgr.setLevel(logging.DEBUG)
fh = logging.handlers.TimedRotatingFileHandler(LOGFILE, when='midnight', interval=1, backupCount=3)
sh = logging.StreamHandler(sys.stdout)
sh.setLevel(logging.DEBUG)
fh.setLevel(logging.DEBUG)
frmt = logging.Formatter(LOG_FORMAT)
fh.setFormatter(frmt)
sh.setFormatter(frmt)
lgr.addHandler(fh)
lgr.addHandler(sh)


def goToSleep(sleepTime):
    lgr.info('Sleeping {} seconds.'.format(sleepTime))
    try:
        time.sleep(sleepTime)
    except KeyboardInterrupt:
        lgr.info('Sleep interrupted.')
        sys.exit()


def checkBackup():
    try:
        lgr.debug('Checking if recall file exists.')
        with open(RECALL, 'r') as f:
            lgr.debug('Recall file found.')
            b = f.read()
    except:
        lgr.debug('Recall file not found.')
        return False
    if 'stop_post' in b:
        lgr.debug('Found command stop_post.')
        time.sleep(5)
        with open(RECALL, 'a') as f:
            f.write('post_waiting\n')
        lgr.info('Pause request received.  Waiting to resume.')
        return True
    return False



def waitForRecall(time):
    lgr.info('Pausing for backup.')
    while True:
        goToSleep(time)
        if not os.path.exists(RECALL):
            lgr.info('Recall file not found, resuming.')
            return


def doProc():
    while True:
        try:
            subprocess.check_call(['php', EXEC_PATH])
        except subprocess.CalledProcessError as e:
            if e.returncode == -2:
                print '\n'
                waitForRecall(600)
            else:
                lgr.error('Crash detected: {}'.format(e))
                goToSleep(120)
                if checkBackup():
                    waitForRecall(600)
        except KeyboardInterrupt:
            print '\n\nInterrupted...\n'
            sys.exit()


if __name__ == '__main__':
    doProc()
